<template>
  <div class="feedback-container">
    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">训练反馈</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="请输入学员姓名"
              style="width: 220px; margin-right: 15px;"
              clearable
              @input="debouncedSearch"
              @clear="handleSearchClear"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="statusFilter"
              placeholder="请选择状态"
              style="width: 130px; margin-right: 15px;"
              @change="handleStatusFilterChange"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="已安排" value="SCHEDULED"></el-option>
              <el-option label="已完成" value="COMPLETED"></el-option>
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        :data="filteredFeedbackList"
        style="width: 100%"
        v-loading="loading"
        class="feedback-table"
      >
        <el-table-column prop="create_at" label="日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.create_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="student_name" label="学员" width="120" />
        <el-table-column prop="program_name" label="训练项目" min-width="150" />
        <el-table-column prop="feedback" label="学员反馈" min-width="150">
          <template #default="scope">
            <div class="content-cell">
              <span>{{ truncateContent(scope.row.feedback, 20) }}</span>
              <el-button
                v-if="scope.row.feedback && scope.row.feedback.length > 20"
                type="text"
                size="small"
                @click="showFullContent(scope.row.feedback)"
              >
                查看全部
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评分" width="120" align="center">
          <template #default="scope">
            <div class="rating-container">
              <el-rate v-model="scope.row.rating" disabled />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="教练回复" min-width="180">
          <template #default="scope">
            <div class="response-cell">
              <span>{{ scope.row.response || '暂无回复' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <div class="operation-buttons" v-if="scope.row.status === 'SCHEDULED'">
              <el-button
                size="small"
                type="success"
                @click="showApproveDialog(scope.row)"
                class="operation-button"
              >
                通过
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="rejectTraining(scope.row)"
                class="operation-button"
              >
                未通过
              </el-button>
            </div>
            <div v-else>
              <el-button
                size="small"
                type="primary"
                @click="showReplyDialog(scope.row)"
                v-if="scope.row.status !== 'COMPLETED'"
                class="operation-button"
              >
                回复
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>

      <!-- 回复对话框 -->
      <el-dialog
        v-model="replyDialogVisible"
        title="回复反馈"
        width="600px"
        class="reply-dialog"
      >
        <el-form
          :model="replyForm"
          :rules="replyRules"
          ref="replyFormRef"
          label-width="80px"
        >
          <el-form-item label="回复内容" prop="response">
            <el-input
              v-model="replyForm.response"
              type="textarea"
              :rows="6"
              placeholder="请输入您的回复内容"
              class="reply-textarea"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="replyDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitReply">提交回复</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 通过确认对话框 -->
      <el-dialog
        v-model="approveDialogVisible"
        title="通过训练"
        width="600px"
        class="approve-dialog"
      >
        <el-form
          :model="approveForm"
          :rules="approveRules"
          ref="approveFormRef"
          label-width="80px"
        >
          <el-form-item label="教练回复" prop="response">
            <el-input
              v-model="approveForm.response"
              type="textarea"
              :rows="6"
              placeholder="请输入教练回复内容"
              class="reply-textarea"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="approveDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitApprove">确认通过</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 内容详情对话框 -->
      <el-dialog
        v-model="contentDialogVisible"
        title="反馈内容详情"
        width="600px"
        class="content-dialog"
      >
        <div class="content-detail">
          <p>{{ fullContent }}</p>
        </div>
        <template #footer>
          <el-button @click="contentDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import requestUtil from '@/util/request.js'
import debounce from 'lodash/debounce'

// 数据和状态
const feedbackList = ref([])
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('') // 状态筛选条件
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表单相关
const replyForm = ref({
  response: ''
})

const replyRules = {
  response: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
}

const replyFormRef = ref(null)

// 通过表单相关
const approveForm = ref({
  response: ''
})

const approveRules = {
  response: [{ required: true, message: '请输入教练回复内容', trigger: 'blur' }]
}

const approveFormRef = ref(null)
const currentApproveRow = ref(null)

// 对话框控制
const replyDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const contentDialogVisible = ref(false)
const selectedFeedback = ref(null)
const fullContent = ref('')
const currentFeedbackId = ref(null)

// 获取训练反馈数据
const fetchFeedbackList = async () => {
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    ElMessage.error('未找到用户信息')
    return
  }

  loading.value = true
  try {
    // 根据用户ID获取该教练相关的反馈（获取所有数据，前端进行分页和过滤）
    const response = await requestUtil.get(`/student_training/trainings/user/${userId}`)

    if (response.data?.status === 200) {
      // 处理数据，提取需要的字段，并过滤掉已取消的记录
      const rawData = (response.data.data || []).filter(item => item.status !== 'CANCELLED')
      const processedData = rawData.map(item => ({
        ...item,
        student_name: item.student_name || item.student?.fullname || '未知学员',
        program_name: item.program_name || item.program?.name || '未知项目'
      }))

      // 保存所有数据
      allFeedbackList.value = processedData
      total.value = processedData.length

      // 更新分页数据
      updatePaginatedData()
    } else {
      ElMessage.error(response.data?.message || '获取反馈列表失败')
      allFeedbackList.value = []
      feedbackList.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取反馈列表失败: ' + (error.message || '未知错误'))
    console.error('获取反馈列表失败:', error)
    allFeedbackList.value = []
    feedbackList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 添加 allFeedbackList 用于存储所有数据
const allFeedbackList = ref([])

// 修改搜索相关逻辑 - 使用前端过滤
const filteredFeedbackList = computed(() => {
  let filtered = allFeedbackList.value

  // 应用搜索过滤
  if (searchQuery.value.trim()) {
    filtered = filtered.filter(feedback =>
      feedback.student_name?.includes(searchQuery.value.trim())
    )
  }

  // 应用状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(feedback =>
      feedback.status === statusFilter.value
    )
  }

  // 更新总数量
  total.value = filtered.length

  // 应用分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 添加更新分页数据的函数
const updatePaginatedData = () => {
  // 触发计算属性重新计算
  // 这里不需要额外操作，因为filteredFeedbackList会自动更新
}

const debouncedSearch = debounce(() => {
  currentPage.value = 1 // 重置到第一页
  // 不需要调用fetchFeedbackList，因为使用前端过滤
}, 300)

// 状态筛选变化处理
const handleStatusFilterChange = () => {
  currentPage.value = 1 // 重置到第一页
  // 不需要调用fetchFeedbackList，因为使用前端过滤
}

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  // 不需要调用fetchFeedbackList，因为使用前端过滤
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  // 不需要调用fetchFeedbackList，因为使用前端过滤
}

// 处理搜索清除
const handleSearchClear = () => {
  searchQuery.value = ''
  currentPage.value = 1
  // 不需要调用fetchFeedbackList，因为使用前端过滤
}


// 显示回复对话框
const showReplyDialog = (feedback) => {
  selectedFeedback.value = feedback
  currentFeedbackId.value = feedback.training_id
  replyForm.value = {
    response: ''
  }
  replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyFormRef.value) return

  try {
    // 验证表单
    await replyFormRef.value.validate()

    const response = await requestUtil.put(`/student_training/trainings/${currentFeedbackId.value}`, {
      response: replyForm.value.response,
      status: 'COMPLETED'
    })

    if (response.data?.status === 200) {
      // 重新获取反馈列表
      await fetchFeedbackList()
      replyDialogVisible.value = false
      ElMessage.success('回复提交成功')
    } else {
      ElMessage.error(response.data?.message || '提交回复失败')
    }
  } catch (error) {
    if (error.field) {
      // 表单验证错误
      return
    }
    ElMessage.error('提交回复失败: ' + (error.message || '未知错误'))
    console.error('提交回复失败:', error)
  }
}

// 显示通过确认对话框
const showApproveDialog = (row) => {
  currentApproveRow.value = row
  approveForm.value = {
    response: ''
  }
  approveDialogVisible.value = true
}

// 提交通过确认
const submitApprove = async () => {
  if (!approveFormRef.value) return

  try {
    // 验证表单
    await approveFormRef.value.validate()

    const response = await requestUtil.put(`/student_training/trainings/update/${currentApproveRow.value.training_id}`, {
      response: approveForm.value.response,
      status: 'COMPLETED'
    })

    if (response.data?.status === 200) {
      ElMessage.success('训练已通过')
      approveDialogVisible.value = false
      await fetchFeedbackList()
    } else {
      ElMessage.error(response.data?.message || '操作失败')
    }
  } catch (error) {
    if (error.field) {
      // 表单验证错误
      return
    }
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    console.error('操作失败:', error)
  }
}

// 拒绝训练
const rejectTraining = async (row) => {
  try {
    await ElMessageBox.confirm(
        '确定要标记为未通过吗？',
        '确认拒绝',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await requestUtil.put(`/student_training/trainings/${row.training_id}`, {
      status: 'CANCELLED',
      content: row.content || '教练未通过'
    })

    if (response.data?.status === 200) {
      ElMessage.success('训练已标记为未通过')
      await fetchFeedbackList()
    } else {
      ElMessage.error(response.data?.message || '操作失败')
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消操作')
      return
    }
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
  }
}

// 截断内容显示
const truncateContent = (content, length) => {
  if (!content) return ''
  if (content.length <= length) return content
  return content.substring(0, length) + '...'
}

// 显示完整内容
const showFullContent = (content) => {
  fullContent.value = content
  contentDialogVisible.value = true
}

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}

// 状态类型映射
const getStatusType = (status) => {
  if (!status) return 'info'
  const upperStatus = status.toUpperCase()
  switch (upperStatus) {
    case 'COMPLETED':
      return 'success'
    case 'SCHEDULED':
      return 'warning'
    case 'CANCELLED':
      return 'danger'
    default:
      return 'info'
  }
}

// 状态文本映射
const getStatusText = (status) => {
  if (!status) return '未知状态'
  const upperStatus = status.toUpperCase()
  switch (upperStatus) {
    case 'COMPLETED':
      return '已完成'
    case 'SCHEDULED':
      return '已安排'
    case 'CANCELLED':
      return '已取消'
    default:
      return status
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchFeedbackList()
})
</script>

<style scoped>
.feedback-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.feedback-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  align-items: center;
}

.feedback-table {
  margin-top: 20px;
}

.feedback-table :deep(.el-table__cell) {
  padding: 8px 0;
}

.feedback-table :deep(.el-table th) {
  font-weight: 600;
  background-color: #f5f7fa;
}

.content-cell {
  display: flex;
  align-items: center;
  gap: 5px;
}

.operation-buttons {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.operation-button {
  margin: 0 2px;
}

.reply-textarea :deep(.el-textarea__inner) {
  resize: none;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.content-detail {
  padding: 20px;
  line-height: 1.6;
}

.content-detail p {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 新增样式：优化评分和教练回复的排版 */
.rating-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 32px;
  padding: 0 8px;
}

.response-cell {
  display: flex;
  align-items: center;
  padding: 0 8px;
  min-height: 32px;
  word-break: break-word;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 减少 ResizeObserver 错误的样式 */
:deep(.el-table) {
  min-height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .feedback-container {
    padding: 10px;
  }

  .feedback-table :deep(.el-table__cell) {
    padding: 5px 0;
  }

  .operation-buttons {
    flex-direction: column;
    gap: 5px;
  }

  .operation-button {
    margin: 2px 0;
  }
}
</style>
